<template>
  <div 
    class="message"
    :class="[
      message.senderId === currentUser.id ? 'user' : 'assistant',
      { selected: isSelected }
    ]"
    @click="$emit('select', index)"
  >
    <div class="message-header">
      <span class="sender">{{ message.senderId === currentUser.id ? 'You' : 'Assistant' }}</span>
      <span class="timestamp">{{ formatTimestamp(message.timestamp) }}</span>
    </div>
    <div class="message-content" v-html="renderedContent"></div>
  </div>
</template>

<script setup>
import { computed } from 'vue';
import MarkdownIt from 'markdown-it';

const props = defineProps({
  message: {
    type: Object,
    required: true
  },
  index: {
    type: Number,
    required: true
  },
  currentUser: {
    type: Object,
    required: true
  },
  isSelected: {
    type: Boolean,
    default: false
  }
});

defineEmits(['select']);

const md = new MarkdownIt({
  html: true,
  breaks: true,
  linkify: true
});

// 渲染消息内容（支持Markdown）
const renderedContent = computed(() => {
  return md.render(props.message.content);
});

// 格式化时间戳
const formatTimestamp = (timestamp) => {
  return new Date(timestamp).toLocaleString();
};
</script>

<style scoped>
.message {
  padding: 16px;
  margin: 8px 0;
  border-radius: 8px;
  position: relative;
  cursor: pointer;
  transition: all 0.2s ease;
}

.message:hover {
  background-color: rgba(0, 0, 0, 0.02);
}

.message.user {
  background-color: #f3f4f6;
  margin-left: 40px;
}

.message.assistant {
  background-color: #ffffff;
  margin-right: 40px;
  border: 1px solid #e5e7eb;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.sender {
  font-weight: 600;
  color: #374151;
}

.timestamp {
  font-size: 0.875rem;
  color: #6b7280;
}

.message-content {
  color: #1f2937;
  line-height: 1.5;
}

.message-content :deep(p) {
  margin: 0.5em 0;
}

.message-content :deep(pre) {
  background-color: #f8f9fa;
  padding: 1em;
  border-radius: 4px;
  overflow-x: auto;
}

.message-content :deep(code) {
  font-family: monospace;
  background-color: #f1f5f9;
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-size: 0.9em;
}

/* 选中状态样式会通过父组件的深度选择器来处理 */
</style>